<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>GetUserMedia</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/static/js/layer.js"></script>
</head>
<body>
<div id="contentHolder">
    <video id="video" width="320" height="320" autoplay hidden>
    </video>
    <canvas id="canvas" width="320" height="320" hidden>
    </canvas>
    <img id="iii"></div>
</div>
</body>
<script type="text/javascript">
    var url="ws://" + window.location.host + "${pageContext.request.contextPath}/video?a=";
    var sock=null;
    var img = document.getElementById('iii');
    var video = document.getElementById('video');
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

    layer.msg("Display or Watch ?", {
        time: 0
        ,btn: ['Display', 'Watch']
        ,yes: function(index){
            sock=new WebSocket(url+"K");
            sock.onopen=function(){
                startCam();
                draw();
            }
            layer.closeAll();
        }
        ,btn2: function(index){
            sock=new WebSocket(url+"W");
            sock.onmessage=function(e){
                //console.log("img:"+e.data.length);
                img.src=e.data;
            }
            layer.closeAll();
        }
    });

    function draw(){
        setInterval(function(){
            context.drawImage(video,0,0,320,320);
            var imgData=canvas.toDataURL();
            //console.log(imgData.length);
            sendImg(imgData);
            //sock.send(imgData.substr(0,8000));
            img.src = canvas.toDataURL();
//            var imgData=context.getImageData(0,0,320,320);
//            for (var i=0;i<imgData.data.length;i+=4)
//            {
//                imgData.data[i]=255-imgData.data[i];
//                imgData.data[i+1]=255-imgData.data[i+1];
//                imgData.data[i+2]=255-imgData.data[i+2];
//                imgData.data[i+3]=255;
//            }
//            context.putImageData(imgData,0,0,320,320);

        },10);
    }

    function sendImg(img) {
        sock.send("start");
        for(var i=0;i<img.length/8000;i++){
            //console.log(img.substr(8000*i,8000));
            sock.send(img.substr(8000*i,8000));
        }
        sock.send("end");
    }

    function startCam(){
        getUserMedia.call(navigator, {
            video: true
        }, function(localMediaStream) {
            video.src = window.URL.createObjectURL(localMediaStream);

        }, function(e) {
            console.log('Reeeejected!', e);
        });
    }
</script>
<html>